﻿using System.Collections.Generic;
using System.Linq;

namespace Results.Models
{
    /// <summary>
    /// Holds all the players that ever participated in a tournament
    /// </summary>
    public class PlayersModel : List<PlayerModel>
    {
        /// <summary>
        /// Create a unique set of players from the list of results
        /// (by extracting unique names)
        /// </summary>
        /// <param name="resultsModel">Source data</param>
        public void Load(ResultsModel resultsModel)
        {
            var playerModel = new PlayerModel();

            // scan all the results, sorted by player name
            // there can be multiple results per player
            foreach (var resultModel in
                from resultModel in resultsModel
                orderby resultModel.LastName, resultModel.FirstName, resultModel.Date descending
                select resultModel)
            {
                // create a new player model if we've moved to a new player's results
                if (playerModel.LastName != resultModel.LastName || playerModel.FirstName != resultModel.FirstName)
                {
                    playerModel = new PlayerModel
                                      {
                                          Hometown = resultModel.Hometown,
                                          GraduationYear = resultModel.GraduationYear,
                                          Gender = (resultModel.Group.ToLower().Contains("women") || resultModel.Group.ToLower().Contains("girl")) ? "F" : "M",
                                          FirstName = resultModel.FirstName,
                                          LastName = resultModel.LastName
                                      };
                    Add(playerModel);
                }

                // two-way link between a player and their results
                resultModel.PlayerModel = playerModel;
                playerModel.Results.Add(resultModel);

                // update missing player info
                if (playerModel.GraduationYear.Length == 0)
                {
                    playerModel.GraduationYear = resultModel.GraduationYear;
                }
            }

            // Sort the players and their results
            foreach (var playerModelToSort in this)
            {
                playerModelToSort.Results.Sort();
            }

            Sort();
        }
    }
}
